import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

function hasUrl(url: string, next: Function) {
  let result = JSON.parse((sessionStorage.getItem('userinfo')) + '').menus_url.some((item: any) => {
    return url == item
  });
  if (result) {
    next()

  } else {
    next('/home')
  }
}
export const routerIndex: Array<RouteRecordRaw> = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    beforeEnter: (to, from, next) => {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    beforeEnter: (to, from, next) => {
      hasUrl('/role', next)
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin/admin.vue'),
    beforeEnter: (to, from, next) => {
      hasUrl('/admin', next)
    }
  },
]
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...routerIndex,
      {
        path: '',
        redirect: '/home'
      },
    ]
  },
  {
    path: '/',
    redirect: '/index'
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next();
    return
  };
  if (sessionStorage.getItem('userinfo')) {
    next();
    return
  }
  next('/login')
})
export default router
